//
//  HTRegisterFirstStepVC.m
//  TruckUser
//
//  Created by Ting Han on 2017/10/17.
//  Copyright © 2017年 Ting Han. All rights reserved.
//

#import "HTRegisterFirstStepVC.h"
#import "HTRegisterSecondStepVC.h"
#import "UIView+Layout.h"
#import "HTMineDetialModel.h"
#import "UIImageView+WebCache.h"
#import "HTImageClipViewController.h"

static NSString *const cargopic = @"cargopic";
static NSString *const carid = @"carid";
static NSString *const card = @"card";
@interface HTRegisterFirstStepVC ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextFieldDelegate,HTImageClipViewControllerDelegate>
//头部
@property (weak, nonatomic) IBOutlet UILabel *driverLabel;
@property (weak, nonatomic) IBOutlet UILabel *truckLabel;
@property (weak, nonatomic) IBOutlet UIView *firstView;
@property (weak, nonatomic) IBOutlet UILabel *firstLabel;
@property (weak, nonatomic) IBOutlet UIView *secondView;
@property (weak, nonatomic) IBOutlet UILabel *secondLabel;
@property (weak, nonatomic) IBOutlet UIView *lineView;

//交互
@property (weak, nonatomic) IBOutlet UITextField *nameTextField;

@property (weak, nonatomic) IBOutlet UITextField *idCardTextField;

@property (weak, nonatomic) IBOutlet UIImageView *identityImageView;

@property (weak, nonatomic) IBOutlet UIImageView *idCardImageView;
@property (weak, nonatomic) IBOutlet UIImageView *cardImageView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollHeight;

@property (weak, nonatomic) IBOutlet UIButton *nextButton;


@property (weak, nonatomic) IBOutlet UILabel *firstHiddenLabel;
@property (weak, nonatomic) IBOutlet UILabel *secondHiddenLabel;

@property (weak, nonatomic) IBOutlet UILabel *thirdHiddenLabel;

@property (nonatomic,copy) NSString *identifyUrl;
@property (nonatomic,copy) NSString *idcardUrl;
@property (nonatomic,copy) NSString *cardUrl;
@property (nonatomic,strong) HTMineDetialModel *mineDetialModel;

@end

@implementation HTRegisterFirstStepVC

- (void)viewDidLoad {
    [super viewDidLoad];
    //未通过，通过
    if (self.isRegister == 3 || self.isRegister == 2) {
        [self netLoadDetialUserInfo];
        if (self.isRegister == 3) {
          [self setupImageViewPicture];
        }else{
            self.nameTextField.userInteractionEnabled = NO;
            self.idCardTextField.userInteractionEnabled = NO;
        }
    }else{//未认证
        [self setupImageViewPicture];
    }
    [self setupHeadView];
    [self setupView];
  
}
- (IBAction)didClickNextButton:(UIButton *)sender {
    if (self.isRegister == 2) {
        HTRegisterSecondStepVC *second = [[HTRegisterSecondStepVC alloc]init];
        second.isRegister = self.isRegister;
        second.mineDetialModel = self.mineDetialModel;
        [self.navigationController pushViewController:second animated:YES];
        return;
    }
    if (self.nameTextField.text == nil || self.nameTextField.text.length <= 0) {
        [HTShowUtil showMessage:@"请输入姓名"];
        return;
    }
    if (self.idCardTextField.text == nil || self.idCardTextField.text.length <= 0) {
        [HTShowUtil showMessage:@"请输入身份证"];
        return;
    }
    if (self.identifyUrl == nil || self.identifyUrl.length <= 0) {
        [HTShowUtil showMessage:@"请上传身份验证照片"];
        return;
    }
    if (self.idcardUrl == nil || self.idcardUrl.length <= 0) {
        [HTShowUtil showMessage:@"请上传身份证照"];
        return;
    }
    if (self.cardUrl == nil || self.cardUrl.length <= 0) {
        [HTShowUtil showMessage:@"请上传名片照"];
        return;
    }
    HTRegisterSecondStepVC *second = [[HTRegisterSecondStepVC alloc]init];
    second.isRegister = self.isRegister;
    second.nameString = self.nameTextField.text;
    second.idcardString = self.idCardTextField.text;
    [self.navigationController pushViewController:second animated:YES];
}
- (void)setupView{
    self.nameTextField.delegate = self;
    self.idCardTextField.delegate = self;
    if (self.nextButton.bottom + 50 < kHTScreenHeight - kHTToolBarHeight - kHTNavicationBarAndStatusBar) {
        self.scrollHeight.constant = kHTScreenHeight;
    }else{
        self.scrollHeight.constant = self.nextButton.bottom + 50;
    }
}
#pragma mark --- headView
- (void)setupHeadView{
    self.title =  @"个人信息";
    self.firstView.layer.masksToBounds = YES;
    self.firstView.layer.cornerRadius = self.firstView.frame.size.width/2;
    self.firstView.layer.borderWidth = 2;
    self.secondView.layer.masksToBounds = YES;
    self.secondView.layer.cornerRadius = self.secondView.frame.size.width/2;
    self.secondView.layer.borderWidth = 2;
    [self setType1Color:kBlueColor];
    [self setType2Color:kMainGrayColor];
}
- (void)setType1Color:(UIColor *)color{
    self.driverLabel.textColor = color;
    self.firstView.layer.borderColor = color.CGColor;
    self.firstLabel.textColor = color;
}
- (void)setType2Color:(UIColor *)color{
    self.truckLabel.textColor = color;
    self.secondView.layer.borderColor = color.CGColor;
    self.secondLabel.textColor = color;
    self.lineView.backgroundColor = color;
}
- (void)setupImageViewPicture{
    self.nameTextField.userInteractionEnabled = YES;
    self.idCardTextField.userInteractionEnabled = YES;
    self.identityImageView.userInteractionEnabled = YES;
    self.idCardImageView.userInteractionEnabled = YES;
    self.cardImageView.userInteractionEnabled  = YES;
    self.identityImageView.tag = 191;
    self.idCardImageView.tag = 192;
    self.cardImageView.tag = 193;
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didCallImage:)];
    [self.identityImageView addGestureRecognizer:tap1];
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didCallImage:)];
    [self.idCardImageView addGestureRecognizer:tap2];
    UITapGestureRecognizer *tap3 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didCallImage:)];
    [self.cardImageView addGestureRecognizer:tap3];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.nameTextField resignFirstResponder];
    [self.idCardTextField resignFirstResponder];
}
-(BOOL) textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

#pragma mark --- 图片处理

- (void)didCallImage:(UITapGestureRecognizer *)sender{
    if (sender.view.tag == 191) {
        [self callActionSheetWithMessage:@"请您上传货主的手持身份证照片" tag:sender.view.tag];
    }else if (sender.view.tag == 192){
        [self callActionSheetWithMessage:@"请您上传货主的身份证照片" tag:sender.view.tag];
    }else if (sender.view.tag == 193){
        [self callActionSheetWithMessage:@"请您上传货主的名片照" tag:sender.view.tag];
    }
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    if(picker.view.tag == 191){
        [self CropImageViewControllerWithImage:portraitImg Frame:CGRectMake(kHTScreenWidth/6, kWidth(90), kHTScreenWidth/3*2, kHTScreenWidth) WithIndex:picker.view.tag withPicker:picker];
    }else if (picker.view.tag == 192){
         [self CropImageViewControllerWithImage:portraitImg Frame:CGRectMake(0, kWidth(90), kHTScreenWidth, kHTScreenWidth/4*3) WithIndex:picker.view.tag withPicker:picker];
    }else if (picker.view.tag == 193){
         [self CropImageViewControllerWithImage:portraitImg Frame:CGRectMake(0, kWidth(90), kHTScreenWidth, kHTScreenWidth/4*3) WithIndex:picker.view.tag withPicker:picker];
    }
}
- (void)CropImageViewControllerWithImage:(UIImage*)portraitImg Frame:(CGRect )rect WithIndex:(NSInteger )index withPicker:(UIImagePickerController *)picker {
    HTImageClipViewController *imgCropperVC = [[HTImageClipViewController alloc] initWithImage:portraitImg cropFrame:rect limitScaleRatio:3.0];
    imgCropperVC.delegate = self;
    imgCropperVC.tag = index;
    [picker pushViewController:imgCropperVC animated:NO];
}
- (void)callActionSheetWithMessage:(NSString *)message tag:(NSInteger)tag{
    [UIAlertController actionSheetStyleShowInController:self title:@"温馨提示" message:message alertActionsBlock:^(NSMutableArray<UIAlertAction *> *alertActions) {
        
        [alertActions addObject:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
            UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
            PickerImage.view.tag = tag;
            PickerImage.sourceType = UIImagePickerControllerSourceTypeCamera;
            PickerImage.allowsEditing = NO;
            PickerImage.delegate = self;
            [self presentViewController:PickerImage animated:YES completion:nil];
        }]];
        [alertActions addObject:[UIAlertAction actionWithTitle:@"本地相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
            PickerImage.view.tag = tag;
            PickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            PickerImage.allowsEditing = NO;
            PickerImage.delegate = self;
            [self presentViewController:PickerImage animated:YES completion:nil];
        }]];
        [alertActions addObject:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    } completion:^{
        
    }];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)imageCropper:(HTImageClipViewController *)clipViewController didFinished:(UIImage *)editedImage{
    switch (clipViewController.tag) {
        case 191:
        {
            self.identityImageView.image = editedImage;
            self.firstHiddenLabel.hidden = YES;
             [self netUpLoadPictureType:cargopic image:editedImage];
            [clipViewController dismissViewControllerAnimated:YES completion:nil];
        }
            break;
        case 192:
        {
            self.idCardImageView.image = editedImage;
            self.secondHiddenLabel.hidden = YES;
            [self netUpLoadPictureType:carid image:editedImage];
            [clipViewController dismissViewControllerAnimated:YES completion:nil];
        }
            break;
        case 193:
        {
            self.cardImageView.image = editedImage;
            self.thirdHiddenLabel.hidden = YES;
            [self netUpLoadPictureType:card image:editedImage];
            [clipViewController dismissViewControllerAnimated:YES completion:nil];
        }
            break;
        default:
            break;
    }
   
}
- (void)imageCropperDidCancel:(HTImageClipViewController *)clipViewController{
    [clipViewController dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark --- 网络请求
- (void)netUpLoadPictureType:(NSString *)type image:(UIImage *)image{
    [self startHud];
    [HTHttpRequestManager requestUploadPictureWithType:type image:image success:^(id  _Nullable responseObject) {
        [self endHud];
        DBLog(@"上传图片：%@",responseObject);
        if (!responseObject) {
            [HTShowUtil showMessage:@"图片保存失败"];
            return ;
        }
        NSString *codeStr = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        if (![codeStr isEqualToString:@"200"]) {
            [HTShowUtil showMessage:responseObject[@"message"]];
            return;
        }
        if ([type isEqualToString:cargopic]) {
            self.identifyUrl = responseObject[@"data"];
        }
        if ([type isEqualToString:carid]) {
            self.idcardUrl = responseObject[@"data"];
        }
        if ([type isEqualToString:card]) {
            self.cardUrl = responseObject[@"data"];
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self endHud];
        [HTShowUtil showMessage:@"图片保存失败"];
    }];
}
- (void)netLoadDetialUserInfo{
    [self startHud];
    [HTHttpRequestManager requestUserInfoDetialsuccess:^(id  _Nullable responseObject) {
        [self endHud];
        DBLog(@"详情用户信息：%@",responseObject);
        if (!responseObject) {
            [HTShowUtil showMessage:@"用户信息获取失败"];
            return ;
        }
        NSString *codeStr = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        if (![codeStr isEqualToString:@"200"]) {
            [HTShowUtil showMessage:responseObject[@"message"]];
            return;
        }
        self.mineDetialModel = [HTMineDetialModel mj_objectWithKeyValues:responseObject[@"data"]];
    } failure:^(NSError * _Nonnull error) {
        [self endHud];
        [HTShowUtil showMessage:@"用户信息获取失败"];
    }];
}
- (void)setMineDetialModel:(HTMineDetialModel *)mineDetialModel{
    _mineDetialModel = mineDetialModel;
    self.nameTextField.text = mineDetialModel.name;
    self.idCardTextField.text = mineDetialModel.carid;
    [self.identityImageView sd_setImageWithURL:[NSURL URLWithString:mineDetialModel.cargopic]];
    self.firstHiddenLabel.hidden = YES;
    [self.idCardImageView sd_setImageWithURL:[NSURL URLWithString:mineDetialModel.carpic]];
    self.secondHiddenLabel.hidden = YES;
    [self.cardImageView sd_setImageWithURL:[NSURL URLWithString:mineDetialModel.card]];
    self.thirdHiddenLabel.hidden = YES;
    self.identifyUrl = mineDetialModel.cargopic;
    self.idcardUrl = mineDetialModel.carpic;
    self.cardUrl = mineDetialModel.card;
}


@end
